package com.kedacom.demo.websocket.rpc;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kedacom.demo.utils.JacksonUtils;

@ServerEndpoint("/websocket/rpc")
public class RPCWebSocketServer {

	private Logger logger = LoggerFactory.getLogger(getClass());

	private static List<Session> sessions = new ArrayList<Session>();

	/**
	 * 连接建立成功调用的方法
	 */
	@OnOpen
	public void onOpen(Session session) {
		sessions.add(session);
		logger.info("有新连接加入，session id：{}，当前在线人数为：{}", session.getId(), sessions.size());
	}

	/**
	 * 连接关闭调用的方法
	 */
	@OnClose
	public void onClose(Session session, CloseReason reason) throws IOException {
		sessions.remove(session);
		logger.info("有连接关闭，session id：{}，关闭原因：{}，当前在线人数为：{}", session.getId(), JacksonUtils.toJsonString(reason),
				sessions.size());
	}

	/**
	 * 收到客户端消息后调用的方法
	 */
	@OnMessage
	public void onMessage(Session session, String message) {
		logger.debug("来自客户端（{}）的消息：{}", session.getId(), message);

		Request request = JacksonUtils.fromJsonString(message, Request.class);
		if (request.getId() == null) {
			// logger.debug("服务器推送消息");
			return;
		}

		// 响应请求
		try {
			Response response = new Response(request.getId(), request.getType(),
					String.format("you said: '%s'", request.getData()));
			sendMessage(session, JacksonUtils.toJsonString(response));
			// logger.debug("已回复消息");
		} catch (IOException e) {
			logger.error("发送请求失败");
			e.printStackTrace();
			return;
		}
	}

	/**
	 * 发生错误时调用
	 */
	@OnError
	public void onError(Session session, Throwable e) {
		logger.error("发生错误，session id：{}，：{}", session.getId(), e.getMessage());
	}

	public void sendMessage(Session session, String message) throws IOException {
		session.getBasicRemote().sendText(message);
	}

}
